/* eslint-disable react/jsx-key */
import React, { useState, useRef } from 'react';
import { Image, Tooltip, Modal, message, Popconfirm } from 'antd';
import AutoTable from '@/components/AutoTable';
import { stopsettle, companydetail, company } from '@/services/business';
import { connect, history } from 'umi';
import moment from 'moment';
import ProDescriptions from '@ant-design/pro-descriptions';
import CompanyName from '@/components/CompanyName';

// type 类型有 table treeselect upload inputnumber datepicker daterange radio select textarea autoinput editor password input

let defaultFields = {
  company_id: {
    value: null,
    type: 'select',
    title: '公司',
    name: ['company_id'],
    required: true,
    options: {
      database: company,
      params: {
        is_all: 1,
      },
    },
  },
  price: {
    value: null,
    type: 'inputnumber',
    title: '续单金额',
    name: ['price'],
    required: true,
  },
  service: {
    value: [],
    type: 'daterange',
    title: '续单服务时间',
    name: ['service'],
    required: true,
    col: { span: 24 },
    format: 'YYYY-MM-DD',
  },
};

let options = [
    {
      //   stalled   未开始         pending   收款中         completed 已完成         cancel    已取消
      id: 'stalled',
      name: '未开始',
    },
    {
      id: 'pending',
      name: '收款中',
    },
    {
      id: 'completed',
      name: '已完成',
    },
    {
      id: 'cancel',
      name: '已取消',
    },
  ],
  valueEnum = {
    stalled: {
      text: '未开始',
    },
    pending: {
      text: '收款中',
    },
    completed: {
      text: '已完成',
    },
    cancel: {
      text: '已取消',
    },
  },
  valueEnums = {
    cache: {
      text: '暂存',
    },
    stalled: {
      text: '未开始',
    },
    dispatching: {
      text: '会计调度中',
    },
    dispatch_refuse: {
      text: '会计调度拒绝',
    },
    accounting: {
      text: '记账会计审核中',
    },
    account_refuse: {
      text: '记账会计拒绝',
    },
    account_cache: {
      text: '记账会计暂存',
    },
    completed: {
      text: '已完成',
    },
  };

function Business(props) {
  const [vs, cvs] = useState(false), //表单显/隐
    [fields, cf] = useState(defaultFields),
    [iftype, ciftype] = useState({}),
    [curkey, setkey] = useState('1');

  let actionRef = useRef(),
    ChildRef = null;
  function reload() {
    actionRef?.current?.reload();
    ChildRef?.onRefresh();
  }

  const columns = [
    {
      title: '公司名称',
      width: 260,
      dataIndex: 'company_name',
      key: 'company_name',
      render: (_, row) => (
        <CompanyName
          row={{ ...row, name: row?.company_name??row.name, id: row?.company_id??row.id }}
          reload={reload}
        />
      ),
    },
    {
      title: '服务开始时间',
      dataIndex: 'service_start_time',
      key: 'service_start_time',
      width: 100,
    },
    {
      title: '服务结束时间',
      dataIndex: 'service_end_time',
      key: 'service_end_time',
      width: 100,
    },
    {
      title: '应收款',
      dataIndex: 'receivable',
      key: 'receivable',
      search: false,
    },
    {
      title: '实际收款',
      dataIndex: 'actual_receive',
      key: 'actual_receive',
      search: false,
    },
    {
      title: '接单时间',
      dataIndex: 'receive_order_time',
      key: 'receive_order_time',
      width: 100,
      render: (dom, row) => {
        return (
          <Tooltip
            title={
              row.receive_order_time
                ? moment(row.receive_order_time).format('YYYY-MM-DD HH:mm:ss')
                : '-'
            }
          >
            <span className="oneline">
              {row.receive_order_time
                ? moment(row.receive_order_time).format('YYYY-MM-DD HH:mm:ss')
                : '-'}
            </span>
          </Tooltip>
        );
      },
    },
    {
      title: '结算月份',
      dataIndex: 'complete_time',
      key: 'complete_time',
      width: 88,
      render: (dom, row) => {
        return (
          <Tooltip title={row.complete_time ? moment(row.complete_time).format('YYYY-MM') : '-'}>
            <span className="oneline">
              {row.complete_time ? moment(row.complete_time).format('YYYY-MM') : '-'}
            </span>
          </Tooltip>
        );
      },
    },
    {
      title: '服务类型',
      dataIndex: 'service_type',
      key: 'service_type',
      render: (dom, row) => {
        return <span>{row.service_type == 'account' ? '代账' : '其他'}</span>;
      },
    },
    {
      title: '首次收款',
      dataIndex: 'is_first',
      key: 'is_first',
      render: (_, row) => {
        return <span>{row.is_first ? '是' : '否'}</span>;
      },
    },
    {
      title: '状态',
      dataIndex: 'status_name',
      key: 'status_name',
      valueType: 'select',
      options: options,
      valueEnum: valueEnum,
      search: false,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 200,
      render: (text, record, _, action) => [
        <a
          onClick={() => {
            cvs(true);
            ciftype({
              ...iftype,
              id: record.id,
              title: (
                <span>
                  收款记录
                  <span style={{ fontSize: 12 }}>(本次应收:{record.receivable})</span>
                </span>
              ),
              val: 'record',
            });
          }}
        >
          收款记录
        </a>,
        <a
          disabled={!['pending', 'stalled'].some((it) => it == record.status)}
          onClick={() => {
            if (!['pending', 'stalled'].some((it) => it == record.status)) {
              return;
            }
            history.push({
              pathname: `/finance/receipt`,
              query: {
                id: record.company_id,
                receivable: record.receivable,
                service: [
                  record.service_start_time ? moment(record.service_start_time) : moment(),
                  record.service_end_time ? moment(record.service_end_time) : moment(),
                ],
                service_type: record.service_type,
              },
            });
          }}
        >
          添加尾款
        </a>,
        <Popconfirm
          placement="bottom"
          title={'确认终止该客户？'}
          onConfirm={() => {
            stopsettle(record.id).then((res) => {
              if (res.code == 0) {
                message.success('操作成功');
                reload();
              }
            });
          }}
          okText="终止"
          disabled={!['pending', 'stalled'].some((it) => it == record.status)}
          cancelText="取消"
        >
          <a
            disabled={!['pending', 'stalled'].some((it) => it == record.status)}
            style={{
              color: !['pending', 'stalled'].some((it) => it == record.status) ? '#999' : '#f50',
            }}
          >
            终止
          </a>
        </Popconfirm>,
      ],
    },
  ];
  const columnes = [
    {
      title: '公司名称',
      width: 260,
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '公司法人',
      dataIndex: 'legal_person',
      key: 'legal_person',
      search: false,
      hideInTable: true,
    },
    {
      title: '公司地址',
      dataIndex: 'address',
      key: 'address',
      search: false,
      hideInTable: true,
    },
    {
      title: '统一社会信用代码',
      dataIndex: 'enterprise_credit_code',
      key: 'enterprise_credit_code',
      search: false,
      hideInTable: true,
    },
    {
      title: '公司营业执照',
      dataIndex: 'origin_url',
      key: 'origin_url',
      render: (_, row) => {
        return <Image width={32} height={32} style={{ padding: 2 }} src={row.origin_url} />;
      },
      hideInTable: true,
      search: false,
    },
    {
      title: '联系人',
      dataIndex: 'customer_name',
      key: 'customer_name',
      ellipsis: true,
    },
    {
      title: '联系人手机号',
      width: 120,
      dataIndex: 'customer_phone',
      key: 'customer_phone',
      render: (_, row) => (
        <Tooltip title={row.customer_phone}>
          <a href={`tel:${row.customer_phone}`} className="oneline">
            {row.customer_phone}
          </a>
        </Tooltip>
      ),
    },
    {
      title: '区域名称',
      dataIndex: 'area_name',
      key: 'area_name',
      search: false,
    },
    {
      title: '区域编码',
      dataIndex: 'area_code',
      key: 'area_code',
      search: false,
      hideInTable: true,
    },
    {
      title: '接单人',
      dataIndex: 'user_name',
      key: 'user_name',
      search: false,
    },
    {
      title: '促单人',
      dataIndex: 'promoter_user_name',
      key: 'promoter_user_name',
      search: false,
    },
    {
      title: '公司类型',
      dataIndex: 'classify_name',
      key: 'classify_name',
      search: false,
    },
    {
      title: '月收费',
      dataIndex: 'unit_price',
      key: 'unit_price',
      search: false,
    },
    {
      title: '活动',
      dataIndex: 'activity_content',
      key: 'activity_content',
      search: false,
      hideInTable: true,
    },
    {
      title: '续单',
      dataIndex: 'is_create_order',
      key: 'is_create_order',
      search: false,
      render: (_, row) => <span>{row.is_create_order ? '是' : '否'}</span>,
    },
    {
      title: '会计流程',
      dataIndex: 'is_accountant',
      key: 'is_accountant',
      search: false,
      render: (_, row) => <span>{row.is_accountant ? '是' : '否'}</span>,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      valueEnum: valueEnum,
      width: 120,
      render: (dom, row) => (
        <div
          style={{
            color: row?.status?.indexOf('refuse') != -1 ? 'red' : 'auto',
            cursor: 'pointer',
          }}
        >
          {valueEnum[row?.status]?.text}
        </div>
      ),
    },
    {
      title: '合同协议',
      dataIndex: 'contracts',
      key: 'contracts',
      search: false,
      render: (_, row) => {
        if (!row.contracts) {
          return (
            <Image
              width={32}
              height={32}
              style={{ padding: 2 }}
              src={require('@/assets/default.png')}
            />
          );
        } else {
          return row.contracts.map((it) => {
            return <Image width={32} height={32} src={it.origin_url} style={{ padding: 2 }} />;
          });
        }
      },
      hideInTable: true,
    },
  ];

  return (
    <div className="pgcontainer">
      <AutoTable
        tabList={[
          {
            key: '1',
            tab: '进行中',
          },
          {
            key: '2',
            tab: '已完成',
          },
          {
            key: '3',
            tab: '已取消',
          },
        ]}
        onTabChange={(val) => {
          setkey(val);
        }}
        pagetitle={props.route.name} //页面标题
        columns={columns}
        actionRef={actionRef}
        onRef={(node) => (ChildRef = node)}
        path="/wbn-api/settle"
        extraparams={{
          status: curkey == '1' ? ['stalled', 'pending'] : curkey == '2' ? 'completed' : 'cancel',
        }}
        //withCard={false}
        //cardtitle = "name" //卡片标题
        //cardavatar = "img_url" //卡片头像
      />

      <Modal
        maskClosable={false}
        title={iftype.title}
        open={vs}
        onCancel={() => cvs(false)}
        footer={false}
        width={1400}
        destroyOnClose={true}
      >
        {iftype.val == 'see' ? (
          <ProDescriptions
            title={`${iftype?.curitem?.name}的详细信息`}
            columns={[...columnes]}
            column={{ xs: 1, sm: 1, md: 2, lg: 3, xl: 4, xxl: 5 }}
            dataSource={iftype?.curitem}
          />
        ) : (
          <AutoTable
            withCard={false}
            columns={[
              {
                title: '本期收费单号',
                dataIndex: 'settle_id',
                key: 'settle_id',
                copyable: true,
                search: false,
                render: (_, row) => (
                  <span>{row.settle_id ? (Array(5).join(0) + row.settle_id).slice(-5) : '-'}</span>
                ),
              },
              {
                title: '公司名称',
                width: 260,
                dataIndex: 'company_name',
                key: 'company_name',
                search: false,
              },
              {
                title: '实际收款',
                dataIndex: 'actual_receive',
                key: 'actual_receive',
                search: false,
              },
              {
                title: '收款日期',
                dataIndex: 'payment_time',
                key: 'payment_time',
                search: false,
              },
              {
                title: '收款类型',
                dataIndex: 'payment_type',
                key: 'payment_type',
                search: false,
                render: (_, row) => {
                  let ops = {
                    full: '全款',
                    deposit: '定金',
                    balance: '尾款',
                  };
                  return ops[row.payment_type];
                },
              },
              {
                title: '结算日期',
                dataIndex: 'settle_time',
                key: 'settle_time',
                search: false,
              },
            ]}
            path={'/wbn-api/settle/' + iftype.id}
            //withCard={false}
            //cardtitle = "name" //卡片标题
            //cardavatar = "img_url" //卡片头像
          />
        )}
      </Modal>
    </div>
  );
}

export default connect(({ business, loading }) => ({
  business,
  loading,
}))(Business);
